//
//  ScanBarCodeViewController.m
//  SXH
//
//  Created by 房 国生 on 15/7/15.
//  Copyright (c) 2015年 lyss. All rights reserved.
//

#import "ScanBarCodeViewController.h"
#import "LPUtils.h"

@interface ScanBarCodeViewController () {
}
@property(nonatomic, strong) UIButton * flashButton;
@end

@implementation ScanBarCodeViewController
@synthesize flashButton;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    UIButton * scanButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [scanButton setBackgroundImage:[UIImage imageNamed:@"scan_back@2x.png"] forState:UIControlStateNormal];
    [self.view addSubview:scanButton];
    [scanButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@20);
        make.top.equalTo(@25);
        make.width.equalTo(@40);
        make.height.equalTo(@40);
    }];
    [scanButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [scanButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    
    
    flashButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [flashButton setBackgroundImage:[UIImage imageNamed:@"flash_on@2x.png"] forState:UIControlStateNormal];
    [self.view addSubview:flashButton];
    [flashButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(@(-20));
        make.top.equalTo(@25);
        make.width.equalTo(@40);
        make.height.equalTo(@40);
    }];
    [flashButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [flashButton addTarget:self action:@selector(flashAction) forControlEvents:UIControlEventTouchUpInside];
    
    
    UILabel * labIntroudction= [[UILabel alloc] init];
    
    labIntroudction.backgroundColor = [UIColor clearColor];
    labIntroudction.numberOfLines=2;
    labIntroudction.textColor=[UIColor whiteColor];
    labIntroudction.textAlignment = NSTextAlignmentCenter;
    labIntroudction.text=@"请将二维码对准扫描区域";
    [self.view addSubview:labIntroudction];
    
    UIImageView *imageView = [[UIImageView alloc]init];
    [self.view addSubview:imageView];
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@40);
        make.right.equalTo(@(-40));
        make.height.equalTo(imageView.mas_width);
        make.centerY.equalTo(self.view);
    }];

    
    imageView.image = [UIImage imageNamed:@"pick_bg"];
    [labIntroudction mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@0);
        make.right.equalTo(@0);
        make.height.equalTo(@50);
        make.top.equalTo(imageView.mas_bottom).offset(5);
    }];
    
    
    upOrdown = NO;
    num =0;
    _line = [[UIImageView alloc] init];
    [self.view addSubview:_line];
    [_line mas_makeConstraints:^(MASConstraintMaker *make) {
        CGFloat Y = (SCREEN_HEIGHT - (SCREEN_WIDTH - 80)) / 2;
        make.left.equalTo(@60);
        make.right.equalTo(@(-60));
        make.height.equalTo(@2);
        make.top.equalTo([NSNumber numberWithFloat:Y]);
    }];
    _line.image = [UIImage imageNamed:@"line.png"];
    
    
    timer = [NSTimer scheduledTimerWithTimeInterval:.02 target:self selector:@selector(animation1) userInfo:nil repeats:YES];
}

-(void)animation1
{
    if (upOrdown == NO) {
        num ++;
        [_line mas_remakeConstraints:^(MASConstraintMaker *make) {
            CGFloat Y = (SCREEN_HEIGHT - (SCREEN_WIDTH - 80)) / 2;
            make.left.equalTo(@60);
            make.right.equalTo(@(-60));
            make.height.equalTo(@2);
            make.top.equalTo(@(Y + 2 * num));
        }];
        if (2*num > SCREEN_WIDTH-100) {
            upOrdown = YES;
        }
    }
    else {
        num --;
        [_line mas_remakeConstraints:^(MASConstraintMaker *make) {
            CGFloat Y = (SCREEN_HEIGHT - (SCREEN_WIDTH - 80)) / 2;
            make.left.equalTo(@60);
            make.right.equalTo(@(-60));
            make.height.equalTo(@2);
            make.top.equalTo(@(Y + 2 * num));
        }];
        if (num == 0) {
            upOrdown = NO;
        }
    }
}

-(void)backAction
{
    [self dismissViewControllerAnimated:YES completion:^{
        [timer invalidate];
    }];
}

-(void)viewWillAppear:(BOOL)animated
{
    [self setupCamera];
}

- (void)setupCamera
{
    // Device
    _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    // Input
    _input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
    
    // Output
    _output = [[AVCaptureMetadataOutput alloc]init];
    [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    // Session
    _session = [[AVCaptureSession alloc]init];
    [_session setSessionPreset:AVCaptureSessionPresetHigh];
    if ([_session canAddInput:self.input])
    {
        [_session addInput:self.input];
    }
    
    if ([_session canAddOutput:self.output])
    {
        [_session addOutput:self.output];
    }
    
    // 条码类型 AVMetadataObjectTypeQRCode
    _output.metadataObjectTypes =@[AVMetadataObjectTypeQRCode];
    
    // Preview
    _preview =[AVCaptureVideoPreviewLayer layerWithSession:self.session];
    _preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
    _preview.frame = self.view.frame;//CGRectMake(0,0,self.f,280);
    [self.view.layer insertSublayer:self.preview atIndex:0];
    
    // Start
    [_session startRunning];
}

#pragma mark AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    
    NSString *stringValue;
    
    if ([metadataObjects count] >0) {
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0];
        stringValue = metadataObject.stringValue;
    }
    
    [_session stopRunning];
    [self dismissViewControllerAnimated:YES completion:^{
         [timer invalidate];
         NSLog(@"%@",stringValue);         
         [_delegate pushScanResultInfo:stringValue];
     }];
}

-(void)flashAction
{
    if (_device.torchMode == AVCaptureTorchModeOff) {
        //Create an AV session
        [_device lockForConfiguration:nil];
        [_device setTorchMode:AVCaptureTorchModeOn];
        [_device unlockForConfiguration];
        [flashButton setBackgroundImage:[UIImage imageNamed:@"flash_off@2x.png"] forState:UIControlStateNormal];
    } else {
        [_device lockForConfiguration:nil];
        [_device setTorchMode:AVCaptureTorchModeOff];
        [_device unlockForConfiguration];
        [flashButton setBackgroundImage:[UIImage imageNamed:@"flash_on@2x.png"] forState:UIControlStateNormal];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
